package com.hejun.redis.controller;

import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping()
public class RedissonController {
    @Resource
    Redisson redisson;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/deduct_stock")
    public String deductStock() {
        String lockKey = "product_001";
        String clientId = UUID.randomUUID().toString();
        RLock redissonLock = redisson.getLock(lockKey);
        try {
            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.SECONDS);
//            if (!result) {
//                return "error";
//            }

            redissonLock.lock(                                                                                                                             30, TimeUnit.SECONDS);
            //这一段是业务逻辑
            Integer stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("扣减失败，库存不足");
            }

        } finally {
            redissonLock.unlock();
//            if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
//                //释放锁
//                stringRedisTemplate.delete(lockKey);
//            }

        }
        return "end";

    }
}
